package dao

import (
	"github.com/xormplus/xorm"
	"shoping.zozoo.net/model"
)

type OrderInterface interface {
	InsertOrder(*model.Order) (int64, error)
	Del(int64) (bool, error)
	Update(*model.Order) (bool, error)
	SelectById(int64) (*model.Order, error)
	SelectAll() ([]*model.Order, error)
	SelectAllWithInfo() ([]*OrderProduct, error)
}

type OrderDao struct {
	*xorm.Engine
}

//关联查询结构体
type OrderProduct struct {
	model.Order   `xorm:"extends"`
	model.Product `xorm:"extends"`
}

func NewOrderDao(orm *xorm.Engine) OrderInterface {
	return &OrderDao{
		orm,
	}
}

//插入订单
func (o *OrderDao) InsertOrder(order *model.Order) (id int64, err error) {
	if id,err = o.Insert(order);err != nil {
		return 0, err
	}

	return order.Id,nil
}

//删除订单
func (o *OrderDao) Del(id int64) (ok bool, err error) {
	var(
		order *model.Order
		)

	order = new(model.Order)
	if _, err = o.ID(id).Delete(order); err != nil {
		return false, err
	}

	return true, nil
}

//修改订单
func (o *OrderDao) Update(order *model.Order) (ok bool, err error) {
	if _, err = o.ID(order.Id).Update(order); err != nil {
		return false, err
	}

	return true, nil
}

//根据id查找订单
func (o *OrderDao) SelectById(id int64) (order *model.Order, err error) {
	order = new(model.Order)
	if _, err = o.ID(id).Get(order); err != nil {
		return nil, err
	}

	return order, nil
}

//查找所有订单
func (o *OrderDao) SelectAll() (list []*model.Order, err error) {
	list = make([]*model.Order, 0)
	if err = o.Find(&list); err != nil {
		return nil, err
	}

	return list, nil
}

//连表查询
func (o *OrderDao) SelectAllWithInfo() (list []*OrderProduct, err error) {
	list = make([]*OrderProduct, 0)
	if err = o.Join("LEFT", "product", "order.id=product.id").Find(list); err != nil {
		return nil, err
	}

	return list, nil
}
